package com.world.cat.service.sys;

import com.world.cat.dao.sys.RoleDao;
import com.world.cat.dao.sys.UserRoleDao;
import com.world.cat.model.sys.Role;
import com.world.cat.model.sys.UserRole;
import com.world.common.pojo.Result;
import com.world.common.util.CollectionUtil;
import com.world.common.util.SysUtil;
import com.world.core.dao.GenericRepository;
import com.world.core.dao.Restrictions;
import com.world.core.dao.SimpleExpression;
import net.sf.json.JSONObject;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Transactional
public class RoleService extends BaseService<Role> {
    private static final Logger logger = Logger.getLogger(RoleService.class);
    public static Map<String, Role> roleIdRoleMap = new ConcurrentHashMap<>();

    @Override
    public GenericRepository getDao() {
        return roleDao;
    }

    @Resource
    private RoleDao roleDao;
    @Resource
    private UserRoleDao userRoleDao;

    public void del(String[] ids) {
        List<SimpleExpression> expressionList = new ArrayList<SimpleExpression>();
        expressionList.add(Restrictions.in("id", CollectionUtil.arrayToSet(ids), true));
        List<Role> roles = roleDao.findAll(expressionList);
        roleDao.deleteInBatch(roles);
        if (CollectionUtil.isNotEmpty(roles)) {
            for (Role role : roles) {
                roleIdRoleMap.remove(role.getId());
            }
        }
    }

    public Result saveRole(Role role) throws Exception {
        if (SysUtil.isEmpty(role.getRoleName())) {
            return new Result(false, "角色名称不能为空!");
        }
        Role roleExist = null;
        if (SysUtil.isEmpty(role.getId())) {//添加
            roleExist = roleDao.findByRoleName(role.getRoleName());
            if (roleExist != null) {
                return new Result(false, "角色已经存在");
            }
            roleExist = new Role();
            roleExist.setRoleKey("ROLE_" + role.getRoleName());
            roleExist.setRoleName(role.getRoleName());
            roleExist = roleDao.save(roleExist);
        } else {//编辑
            roleExist = roleDao.getOne(role.getId());
            if (roleExist != null) {
                roleExist.setRoleKey("ROLE_" + role.getRoleName());
                roleExist.setRoleName(role.getRoleName());
                roleExist = roleDao.save(roleExist);
            } else {
                return new Result(false, "角色不存在");
            }
        }

        return new Result(true, "成功", roleExist);
    }

    public Role getRole(String id) {
        return roleDao.findOne(id);
    }

    //一上来就删除所有的角色，后面再添加的时候会出现主键冲突，因为删除的操作并没有执行，好像要加个flush才行，先这样吧
    public void saveUserRole(String userId, String[] roleIds) {
        List<UserRole> userRoles = userRoleDao.findByUserId(userId);
        Map<String, UserRole> roleIdUserRoleMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(userRoles)) {
            for (UserRole userRole : userRoles) {
                roleIdUserRoleMap.put(userRole.getRoleId(), userRole);
            }
        }
        if (ArrayUtils.isNotEmpty(roleIds)) {
            List<UserRole> userRolesNew = new ArrayList<>();
            for (String roleId : roleIds) {
                if (roleIdUserRoleMap.keySet().contains(roleId)) {
                    roleIdUserRoleMap.remove(roleId);
                } else {
                    UserRole userRole = new UserRole();
                    userRole.setRoleId(roleId);
                    userRole.setUserId(userId);
                    userRolesNew.add(userRole);

                }
            }
            List<UserRole> userRoles1 = userRoleDao.save(userRolesNew);
            //更新缓存
            for (UserRole userRole : userRoles1) {
                UserRoleService.userRoleMap.put(userRole.getId(), userRole);
            }
        }
        userRoleDao.delete(roleIdUserRoleMap.values());
        //更新缓存
        for (UserRole userRole : roleIdUserRoleMap.values()) {
            UserRoleService.userRoleMap.remove(userRole.getId());
        }
    }

    public List<Role> getAll() {
        return roleDao.findAll();
    }

    public void initRoleCache() {
        logger.info("初始化角色数据开始--------------------------------");
        List<Role> os = roleDao.findAll();
        if (CollectionUtil.isNotEmpty(os)) {
            for (Role o : os) {
                RoleService.roleIdRoleMap.put(o.getId(), o);
            }
        }
        logger.info("初始化角色数据结束--------------------------------");
    }
}
